//
// Created by v on 19-6-25.
//

#include "CMConfigSimple.h"

CMConfigSimple::CMConfigSimple(const char *filename)
{
    m_filename = filename;
    int ret    = cm_config_read_ex(filename, m_list);
    if (ret > 0)
    {
        m_valid = true;
    }
    else
    {
        m_valid = false;
    }
}

int CMConfigSimple::writeBack()
{
    return cm_config_write_ex(m_filename.c_str(), m_list);
}

int CMConfigSimple::getInt(const char *key)
{
    std::string v = m_list[key];
    if (v.empty())
        return CONF_ERROR_NOT_EXIST;
    return strtol(v.c_str(), NULL, 10);
}

int CMConfigSimple::getString(const char *key, std::string &result)
{
    std::string v = m_list[key];
    if (v.empty())
        return -1;
    result = v;
    return 0;
}

int CMConfigSimple::getBool(const char *key, bool &result)
{
    std::string v = m_list[key];
    if (v.empty())
        return CONF_ERROR_NOT_EXIST;
    if (v == "false" || v == "0")
        result = false;
    else
        result = true;
    return 0;
}

int CMConfigSimple::getDouble(const char *key, double &result)
{
    std::string v = m_list[key];
    if (v.empty())
        return CONF_ERROR_NOT_EXIST;
    result = strtod(v.c_str(), NULL);
    return 0;
}

int CMConfigSimple::setString(const char *key, const std::string &value)
{
    m_list[key] = value;
    return 0;
}
